<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms 
of the GNU General Public License as published by the Free Software Foundation; either 
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; 
if not, write to the 
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2007
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
*	CITE class.
*
*	Citation handling
* 
* $Header: /cvsroot/wikindx/wikindx3/core/cite/CITE.php,v 1.38 2007/07/06 13:38:09 sirfragalot Exp $
*****/

/*
This is the main file to handle citations.

For users with javascript turned off, the hyperlinks to this page should not display at all.
*/

class CITE
{
// Constructor
	function CITE($db, $vars)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/html/HTML.php");
		$this->html = new HTML();
		include_once("core/html/MISC.php");
		$this->html = new MISC();
		include_once("core/html/CLOSEPOPUP.php");
		include_once("core/html/MISC.php");
		include_once("core/html/FORM.php");
		include_once("core/html/TABLE.php");
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		$this->cite = FALSE;
	}
// display search form for citation insertion
	function display($error = FALSE)
	{
		$this->template->setVar("heading", $this->messages->text("heading", "citations"));
//First check, do we have resources?
		$recordset = $this->db->select(array('WKX_database_summary'), array('totalResources'));
		if(!$this->db->fetchOne($recordset))
		{
			$this->template->setVar('body', $this->messages->text('misc', 'noResources'));
			$this->template->process();
			new CLOSEPOPUP($this->template->process());
		}
		$pString = $this->displayForm($error);
		$this->template->setVar('body', $pString);
		new CLOSEPOPUP($this->template->process());
	}
// display form
	function displayForm($error = FALSE)
	{
		$this->userBib = $this->session->getVar("mywikindx_bibliography_use");
		$bib = FALSE;
		if($this->userBib)
		{
			$recordset = $this->db->select(array('WKX_user_bibliography'), array('title'), 
				" WHERE " . $this->db->formatfield('id') . "=" . $this->db->tidyInput($this->userBib));
			$row = $this->db->fetchRow($recordset);
			$bib = MISC::p(MISC::span("(" . $this->messages->text("user", "bibliography") . ": " . 
				$row['title'] . ")", "hint"));
		}
		else if($this->session->getVar('setup_multiUser'))
			$bib = MISC::p(MISC::span("(" . $this->messages->text("user", "bibliography") . ": " . 
			$this->messages->text("user", "masterBib") . ")", "hint"));
// load the session
		$sessionVars = $this->session->getArray("citeSearch");
		$pString = $error ? $error : FALSE;
		$pString .= $bib;
		$pString .= FORM::formHeader("citeSearchProcess");
		if(array_key_exists('citeMethod', $this->vars)) // i.e. coming from SUWP so requires different javascript calls (see below)
			$pString .= FORM::hidden('citeMethod', 'suwp');
		$pString .= TABLE::tableStart();
		$pString .= TABLE::trStart();
		$this->grabCreators();
		if($this->creator)
			$pString .= TABLE::td($this->makeFormMultiple("creator", $this->creator));
		else
			$pString .= TABLE::td("&nbsp;");
// There may not yet be keywords in the database.
		$this->grabKeywords();
		if($this->keyword)
			$pString .= TABLE::td($this->makeFormMultiple("keyword", $this->keyword));
		else
			$pString .= TABLE::td("&nbsp;");
		$pString .= TABLE::td("&nbsp;");
		$pString .= TABLE::td("&nbsp;");
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		$pString .= MISC::hr();
		$pString .= TABLE::tableStart();
		$pString .= TABLE::trStart();
// array of database fields that can be searched on:
		$fields = array("title"	=>	$this->messages->text("search", "title"),
				"note"		=>	$this->messages->text("search", "note"),
				"abstract"	=>	$this->messages->text("search", "abstract"),
				"quote"	=>	$this->messages->text("search", "quote"),
				"paraphrase"	=>	$this->messages->text("search", "paraphrase"),
				"musing"	=>	$this->messages->text("search", "musing"),
			);
		$this->makeRadioButtons('field');
		$pString .= TABLE::td($this->makeFormMultiple("field", $fields, TRUE));
		$this->radioButtons = FALSE;
		$word = $this->session->issetVar("citeSearch_word") ? 
			stripslashes($this->session->getVar("citeSearch_word")) : FALSE;
		$checked = $this->session->issetVar("citeSearch_partial") ? 'CHECKED' : FALSE;
		$pString .= TABLE::td(FORM::textInput($this->messages->text("search", "word"), "citeSearch_word", 
			$word, 40) . MISC::p($this->messages->text("search", "partial") . ":&nbsp;&nbsp;" . 
			FORM::checkbox(FALSE, "citeSearch_partial", $checked)));
// array of search methods:
		$methods = array("OR"		=>	"OR",
				"AND"		=>	"AND",
				"exact"		=>	$this->messages->text("search", "exact"),
			);
		if($selected = $this->session->getVar("citeSearch_method"))
			$pString .= TABLE::td(FORM::selectedBoxValue(
			$this->messages->text("search", "search", " " . 
			$this->messages->text("search", "method")), "citeSearch_method", $methods, $selected, 3));
		else
			$pString .= TABLE::td(FORM::selectFBoxValue(
			$this->messages->text("search", "search", " " . 
			$this->messages->text("search", "method")), "citeSearch_method", $methods, 3));
		if(array_key_exists('citeMethod', $this->vars)) // i.e. SUWP form
		{
			$this->session->clearArray("citeSearch");
			$reset = MISC::br() . MISC::br() . FORM::formHeader("citeDisplay") . 
				FORM::hidden('citeMethod', 'suwp') .
				FORM::formSubmit("Reset") . FORM::formEnd();
		}
		else
		{
			$this->session->clearArray("citeSearch");
			$reset = MISC::br() . MISC::br() . FORM::formHeader("citeDisplay") . 
				FORM::formSubmit("Reset") . FORM::formEnd();
		}
		$pString .= TABLE::td(FORM::formSubmit("Search") . FORM::formEnd() . $reset, FALSE, FALSE, "bottom");
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		return $pString;
	}
// make a multiple select box
	function makeFormMultiple($type, $array, $noIgnore = FALSE)
	{
// add 0 => IGNORE to $array
		if(!$noIgnore)
		{
			$temp[0] = $this->messages->text("misc", "ignore");
			foreach($array as $key => $value)
				$temp[$key] = $value;
		}
		else
			$temp = $array;
		if($type == 'keyword')
			$label = 'member';
		else
			$label = 'search';
		if($selected = $this->session->getVar("citeSearch_" . $type))
		{
			$selectedArray = explode(",", $selected);
			$pString = FORM::selectedBoxValueMultiple(
				$this->messages->text("search", $label, " " . 
				$this->messages->text("search", $type)), 
				"citeSearch_" . $type, $temp, $selectedArray, 5);
		}
		else
		{
// If $type == 'field', select all fields as default
			if($type == 'field')
			{
				$pString = FORM::selectedBoxValueMultiple(
					$this->messages->text("search", $label, " " . 
					$this->messages->text("search", $type)), 
					"citeSearch_" . 'field', $temp, array_keys($array), 5);
			}
			else
				$pString = FORM::selectFBoxValueMultiple(
					$this->messages->text("search", $label, " " . 
					$this->messages->text("search", $type)), 
					"citeSearch_" . $type, $temp, 5);
		}
		$pString .= MISC::br() . $this->messages->text("hint", "multiples") . MISC::br();
		$pString .= $this->radioButtons . MISC::br();
		return $pString;
	}
// get keywords from database.
	function grabKeywords()
	{
		include_once("core/keyword/KEYWORD.php");
		$keyword = new KEYWORD($this->db);
		$userBib = $this->session->getVar("mywikindx_bibliography_use");
		$this->keyword = $keyword->grabAll($userBib);
		$this->makeRadioButtons('keyword');
	}
// get creators from database.
	function grabCreators()
	{
		include_once("core/html/FORM.php");
		include_once("core/creator/CREATOR.php");
		$creator = new CREATOR($this->db);
		$this->creator = $creator->grabAll($this->userBib);
		$this->makeRadioButtons('creator');
	}
// Create radio buttons for AND and OR
	function makeRadioButtons($type)
	{
		$type = 'citeSearch_' . $type . 'Method';
		if($this->session->getVar($type) == 'AND')
		{
			$pString = MISC::span(FORM::radioButton(FALSE, $type, 'OR') . " OR", "small") . MISC::br();
			$pString .= MISC::span(FORM::radioButton(FALSE, $type, 'AND', TRUE) . " AND", "small");
		}
// Default
		else
		{
			$pString = MISC::span(FORM::radioButton(FALSE, $type, 'OR', TRUE) . " OR", "small") . 
				MISC::br();
			$pString .= MISC::span(FORM::radioButton(FALSE, $type, 'AND') . " AND", "small");
		}
		$this->radioButtons = $pString;
	}
// Display results of search
	function citeSearchProcess()
	{
		$input = $this->checkInput();
		include_once("core/styles/BIBSTYLE.php");
		$bibStyle = new BIBSTYLE($this->db, "html");
		include_once("core/sql/STATEMENTS.php");
		$stmt = new STATEMENTS($this->db);
		$this->fieldArray = $stmt->listFields();
		$this->fieldArray = array_merge($this->fieldArray, array("surname")); // for ordering purposes
		$condition = " WHERE ";
		if(array_key_exists('creator', $input))
		{
			include_once("core/creator/CREATOR.php");
			$creator = new CREATOR($this->db);
			$this->conditionArray[] = "(" . $creator->selectCondition(array('creator' => $input['creator'], 
				'creatorMethod' => $input['creatorMethod'])) . ")";
		}
		if(array_key_exists('keyword', $input))
		{
			include_once("core/keyword/KEYWORD.php");
			$keyword = new KEYWORD($this->db);
			$this->conditionArray[] = "(" . $keyword->selectCondition(array('keyword' => $input['keyword'], 
				'keywordMethod' => $input['keywordMethod'])) . ")";
		}
		$this->joinStmt = $stmt->selectJoin();
		if(array_key_exists('word', $input))
			$this->parseWord($input);
		$condition .= join(' AND ', $this->conditionArray);
		$this->template->setVar("heading", $this->messages->text("heading", "citations"));
		include_once("core/list/LISTCOMMON.php");
		$this->common = new LISTCOMMON($this->db, $this->vars);
		if($userBibCondition = $this->common->userBibCondition())
			$condition .= " AND (" . $userBibCondition . ")";
		$order = " ORDER BY " . $this->db->tidyInputClause('surname') . ", " . 
			$this->db->formatField('firstname') . 
			", " . $this->db->formatField("WKX_resource.title") . 
			", " . " COALESCE(" . $this->db->formatField('year1') . 
			", " . $this->db->formatField('year2') . 
			", " . $this->db->formatField('year3') . ")";
		$recordSet = $this->db->select(array('WKX_resource'), $this->fieldArray, $this->joinStmt . 
			$condition . " GROUP BY " . $this->db->tidyInputClause("resourceId") . " " . $order);
		$pString = $this->displayForm() . MISC::hr();
// Table elements from enclosing table in template
//		$pString .= TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();
//		$pString = '';
		if($this->db->numRows($recordSet))
		{
			$pString .= TABLE::tableStart();
			$pString .= FORM::formHeaderName("", "js", "onsubmit=\"submitForm();\"");
			$radioButtonFirst = TRUE;
			$index = 0;
			while($row = $this->db->loopRecordSet($recordSet))
			{
				$class = $index % 2 ? 'alternate2' : 'alternate1';
				$pString .= TABLE::trStart();
				$pString .= TABLE::td($bibStyle->process($row), $class);
				if($radioButtonFirst)
				{
					$pString .= TABLE::td(FORM::radioButton(FALSE, 'cite', $row['resourceId'], TRUE), 
						$class, 'right');
					$radioButtonFirst = FALSE;
				}
				else
					$pString .= TABLE::td(FORM::radioButton(FALSE, 'cite', $row['resourceId']), 
						$class, FALSE, 'right');
				$pString .= TABLE::trEnd();
				++$index;
			}
// Create optional page start and page end boxes and submit button.
			$pString .= TABLE::tableEnd();
// Table elements from enclosing table in template
			$pString .= TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();
			$pString .= TABLE::tableStart() . TABLE::trStart();
			$pString .= TABLE::td(FORM::textInput($this->messages->text("resources", "page"), 'pageStart', 
				FALSE, 6, 5) . " - " . FORM::textInput(FALSE, 'pageEnd', FALSE, 6, 5), FALSE, FALSE, "bottom");
// preText and postText for the citation (usually appears within citation parentheses but will be ignored for endnote-style citations)
			$pString .= TABLE::td($this->messages->text("cite", "preText") . "&nbsp;&nbsp;" . 
				FORM::textInput(FALSE, 'preText', FALSE, 12) . ",&nbsp;&nbsp;" . 
				$this->messages->text("cite", "postText") . "&nbsp;&nbsp;" . 
				FORM::textInput(FALSE, 'postText', FALSE, 12), FALSE, FALSE, "bottom");
			$pString .= TABLE::td(FORM::formSubmit("Cite") . FORM::formEnd(), FALSE, FALSE, "bottom");
			$pString .= TABLE::trEnd() . TABLE::tableEnd();
// Include JavaScript file if this is not for SUWP
			if(!array_key_exists('citeMethod', $this->vars))
			{
				$execute = "function submitForm() {\n  var citeForm = document.getElementsByTagName('form').item('js');\n var citeString = handleCiteForm(citeForm);\n}";
				$pString .= MISC::jsExternal('core/cite/cite.js', $execute);
			}
			else if($this->vars['citeMethod'] == 'suwp') // SUWP citation/metadata inserts
			{
				$execute = "function submitForm() {\n  var citeForm = document.getElementsByTagName('form').item('js');\n  var citeString = handleCiteFormRte(citeForm);\n  window.opener.insertCiteStringRte(citeString);\n  window.close();\n}";
				$pString .= MISC::jsExternal('core/wp/JsFormatBar/JavaScript/JavaScript.js', $execute);
			}
			$this->template->setVar('body', $pString);
			new CLOSEPOPUP($this->template->process());
		}
		else
			$this->badInput($this->messages->text('resources', 'noResult'));
	}
// parse the search word(s)
	function parseWord($input)
	{
		include_once("core/messages/UTF8.php");
		$utf8 = new UTF8();
		if(($input['method'] == 'OR') || ($input['method'] == 'AND'))
			$string = explode(" ", $utf8->smartUtf8_encode(trim($input['word'])));
		else
			$string = array($utf8->smartUtf8_encode(trim($input['word'])));
		$this->session->setVar("searchMeta_highlight", implode(",", $string));
// partial or complete word searching?
		if(array_key_exists('partial', $input))
		{
			foreach($string as $word)
				$this->words[] = " LIKE '%" . trim($word) . "%'";
		}
		else
		{
			foreach($string as $word)
				$this->words[] = " REGEXP '[[:<:]]" . trim($word) . "[[:>:]]'";
		}
		$fields = split(',', $input['field']);
		foreach($fields as $field)
		{
			$condition = array();
			if($field == 'title')
			{
				foreach($this->words as $word)
					$condition[] = $this->db->formatField('WKX_resource.title') . $word . 
						" OR " . 
						$this->db->formatField('subtitle') . $word;
				$conditionArray[] = "(" . implode(' ' . $input['method'] . ' ', $condition) . ")";
			}
			else if($field == 'note')
			{
				$this->fieldArray = array_merge($this->fieldArray, 
					array(array('WKX_resource_note.text' => "note")));
				foreach($this->words as $word)
					$condition[] = 'WKX_resource_note.text' . $word;
				$conditionArray[] = "(" . implode(' ' . $input['method'] . ' ', $condition) . ")";
			}
			else if($field == 'abstract')
			{
				$this->fieldArray = array_merge($this->fieldArray, array('abstract'));
				foreach($this->words as $word)
					$condition[] = 'WKX_resource_abstract.abstract' . $word;
				$conditionArray[] = "(" . implode(' ' . $input['method'] . ' ', $condition) . ")";
			}
			else if($field == 'quote')
			{
				$this->fieldArray = array_merge($this->fieldArray, 
					array(array('WKX_resource_quote_text.text' => "quote"),
						array('WKX_resource_quote_comment.comment' => "quoteComment")));
				$this->joinStmt .= " LEFT JOIN " . $this->db->formatTable("WKX_resource_quote") .  
					" ON " . $this->db->formatfield("WKX_resource.id") . "=" . 
					$this->db->formatfield("WKX_resource_quote.resourceId") .  
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_quote_text") .  
					" ON " . $this->db->formatfield("WKX_resource_quote.id") . "=" . 
					$this->db->formatfield("WKX_resource_quote_text.id") . 
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_quote_comment") . 
					" ON " . $this->db->formatfield("WKX_resource_quote.id") . "=" . 
					$this->db->formatfield("WKX_resource_quote_comment.quoteId");
				foreach($this->words as $word)
					$condition[] = $this->db->formatfield("WKX_resource_quote_text.text") . 
					$word . ' OR ' . 
					$this->db->formatfield("WKX_resource_quote_comment.comment") . $word;
				$conditionArray[] = "(" . implode(' ' . $input['method'] . ' ', $condition) . ")";
			}
			else if($field == 'paraphrase')
			{
				$this->fieldArray = array_merge($this->fieldArray, 
					array(array('WKX_resource_paraphrase_text.text' => "paraphrase"),
						array('WKX_resource_paraphrase_comment.comment' => "paraphraseComment")));
				$this->joinStmt .= " LEFT JOIN " . $this->db->formatTable("WKX_resource_paraphrase") .  
					" ON " . $this->db->formatfield("WKX_resource.id") . "=" . 
					$this->db->formatfield("WKX_resource_paraphrase.resourceId") .  
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_paraphrase_text") .  
					" ON " . $this->db->formatfield("WKX_resource_paraphrase.id") . "=" . 
					$this->db->formatfield("WKX_resource_paraphrase_text.id") .  
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_paraphrase_comment") . 
					" ON " . $this->db->formatfield("WKX_resource_paraphrase.id") . "=" . 
					$this->db->formatfield("WKX_resource_paraphrase_comment.paraphraseId");
				foreach($this->words as $word)
					$condition[] = $this->db->formatfield("WKX_resource_paraphrase_text.text") . 
					$word . ' OR ' . 
					$this->db->formatfield("WKX_resource_paraphrase_comment.comment") . $word;
				$conditionArray[] = "(" . implode(' ' . $input['method'] . ' ', $condition) . ")";
			}
			else if($field == 'musing')
			{
				$this->fieldArray = array_merge($this->fieldArray, 
					array(array('WKX_resource_musing_text.text' => "musing")));
				$this->joinStmt .= " LEFT JOIN " . $this->db->formatTable("WKX_resource_musing") . 
					" ON " . $this->db->formatfield("WKX_resource.id") . "=" . 
					$this->db->formatfield("WKX_resource_musing.resourceId") .  
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_musing_text") .  
					" ON " . $this->db->formatfield("WKX_resource_musing.id") . "=" . 
					$this->db->formatfield("WKX_resource_musing_text.id");
				foreach($this->words as $word)
					$condition[] = $this->db->formatfield("WKX_resource_musing_text.text") . $word;
				$conditionArray[] = "(" . implode(' ' . $input['method'] . ' ', $condition) . ")";
			}
		}
		if(isset($conditionArray))
			$this->conditionArray[] = "(" . implode(' ' .  $input['fieldMethod'] . ' ', $conditionArray) . ")";
	}
// display the citation pop-up window with radio buttons of found resources, page number text boxes and submit button.
// $this->vars['method'] will be 'abstract', 'note', 'musing', 'quote', 'quoteComment', 'paraphrase' or 'paraphraseComment' 
// referring to the textarea box into which to insert the citation.  Abstract, notes and musings have one textarea, quotes 
// and paraphrases have two (the quote/paraphrase and its comment).
// NOT USED ANYMORE
	function displayResults()
	{
die;
		$pString = '';
		$this->template->setVar("heading", $this->messages->text("heading", "citations"));
		include_once("core/list/LISTCOMMON.php");
		$this->common = new LISTCOMMON($this->db, $this->vars);
		include_once("core/styles/BIBSTYLE.php");
		$bibStyle = new BIBSTYLE($this->db, "plain");
		include_once("core/sql/STATEMENTS.php");
		$stmt = new STATEMENTS($this->db);
		if($userBibCondition = $this->common->userBibCondition())
			$userBibCondition = " WHERE " . $userBibCondition;
		$recordset = $this->db->select(array("WKX_resource"), $stmt->listFields('creator'), 
			$stmt->listJoin('creator', $userBibCondition));
		while($row = $this->db->loopRecordSet($recordset))
			$select[$row['resourceId']] = $bibStyle->process($row, TRUE);
		if(isset($select))
		{
			$pString .= FORM::formHeader("", "onsubmit=\"submitForm();\"");
// Create select box
			$pString .= FORM::selectFBoxValue(FALSE, "cite", $select, "30", "120");
			$pString .= TABLE::tableStart() . TABLE::trStart();
// Create optional page start and page end boxes and submit button.
			$pString .= TABLE::td(FORM::textInput($this->messages->text("resources", "page"), 'pageStart', 
				FALSE, 6, 5) . " - " . FORM::textInput(FALSE, 'pageEnd', FALSE, 6, 5), FALSE, FALSE, "bottom");
// preText and postText for the citation (usually appears within citation parentheses but will be ignored for endnote-style citations)
			$pString .= TABLE::td($this->messages->text("cite", "preText") . "&nbsp;&nbsp;" . 
				FORM::textInput(FALSE, 'preText', FALSE, 12) . ",&nbsp;&nbsp;" . 
				$this->messages->text("cite", "postText") . "&nbsp;&nbsp;" . 
				FORM::textInput(FALSE, 'postText', FALSE, 12), FALSE, FALSE, "bottom");
			$pString .= TABLE::td(FORM::formSubmit("Cite"), FALSE, FALSE, "bottom");
			$pString .= TABLE::tdEnd() . TABLE::tableEnd();
			$pString .= FORM::formEnd();
// Include JavaScript file if this is not for SUWP
			if(array_key_exists('method', $this->vars) && ($this->vars['method'] != 'suwp'))
				$pString .= MISC::jsExternal('core/cite/cite.js');
			else // SUWP citation/metadata inserts
			{
				$execute = "function submitForm() {\n  var citeForm = document.getElementsByTagName('form').item(0);\n  var citeString = handleCiteFormRte(citeForm);\n  window.opener.insertCiteStringRte(citeString);\n  window.close();\n}";
				$pString .= MISC::jsExternal('core/wp/JsFormatBar/JavaScript/JavaScript.js', $execute);
			}
		}
		else
			$pString = $this->messages->text("misc", "noResources");
		$this->template->setVar('body', $pString);
		new CLOSEPOPUP($this->template->process());
	}
// Make the citation hyperlink (for meta data inserts -- not for SUWP)
	function makeCiteLink($method)
	{
		include_once("core/icons/LOADICONS.php");
		$icons = new LOADICONS();
		$icons->getIconInfo("cite");
		$linkStyle = $icons->citeExists ? "imgLink linkCiteHidden" : "link linkCiteHidden";
		return "&nbsp;&nbsp;" . MISC::a($linkStyle, $icons->cite, 
			"javascript:openCiteWindow('index.php?action=citeDisplay" . "&amp;method=$method')"); // link is actually a JavaScript call
	}
// show citations about this resource
	function showCitations($resourceId)
	{
		$pString = FALSE;
		$search1 = "\\[cite\\]$resourceId\\[";
		$search2 = "\\[cite\\]$resourceId:";
		$search3 = "\\[cite\\]$resourceId|";
		$sql = $this->db->selectNoExecute(
			array("WKX_resource"), array(array("WKX_resource.id" => "resourceId", 
			"WKX_resource_note.text" => "note")), 
			" LEFT JOIN " . $this->db->formatTable("WKX_resource_abstract") . 
				" ON " . $this->db->formatField("WKX_resource.id") . "=" . 
				$this->db->formatField("WKX_resource_abstract.id") . 
			" LEFT JOIN " . $this->db->formatTable("WKX_resource_note") . 
				" ON " . $this->db->formatField("WKX_resource.id") . "=" . 
				$this->db->formatField("WKX_resource_note.id") . 
			" LEFT JOIN " . $this->db->formatTable("WKX_resource_quote") . 
				" ON " . $this->db->formatField("WKX_resource.id") . "=" . 
				$this->db->formatField("WKX_resource_quote.resourceId") . 
			" LEFT JOIN " . $this->db->formatTable("WKX_resource_quote_text") . 
				" ON " . $this->db->formatField("WKX_resource_quote.id") . "=" . 
				$this->db->formatField("WKX_resource_quote_text.id") . 
			" LEFT JOIN " . $this->db->formatTable("WKX_resource_quote_comment") . 
				" ON " . $this->db->formatField("WKX_resource_quote.id") . "=" . 
				$this->db->formatField("WKX_resource_quote_comment.quoteId") . 
			" LEFT JOIN " . $this->db->formatTable("WKX_resource_paraphrase") . 
				" ON " . $this->db->formatField("WKX_resource.id") . "=" . 
				$this->db->formatField("WKX_resource_paraphrase.resourceId") . 
			" LEFT JOIN " . $this->db->formatTable("WKX_resource_paraphrase_text") . 
				" ON " . $this->db->formatField("WKX_resource_paraphrase.id") . "=" . 
				$this->db->formatField("WKX_resource_paraphrase_text.id") . 
			" LEFT JOIN " . $this->db->formatTable("WKX_resource_paraphrase_comment") . 
				" ON " . $this->db->formatField("WKX_resource_paraphrase.id") . "=" . 
				$this->db->formatField("WKX_resource_paraphrase_comment.paraphraseId") . 
			" LEFT JOIN " . $this->db->formatTable("WKX_resource_musing") . 
				" ON " . $this->db->formatField("WKX_resource.id") . "=" . 
				$this->db->formatField("WKX_resource_musing.resourceId") . 
			" LEFT JOIN " . $this->db->formatTable("WKX_resource_musing_text") . 
				" ON " . $this->db->formatField("WKX_resource_musing.id") . "=" . 
				$this->db->formatField("WKX_resource_musing_text.id") . 
			" WHERE (" . 
					$this->db->formatField("WKX_resource_abstract.abstract") . 
					" LIKE " . $this->db->tidyInput("%$search1%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_abstract.abstract") . 
					" LIKE " . $this->db->tidyInput("%$search2%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_abstract.abstract") . 
					" LIKE " . $this->db->tidyInput("%$search3%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_note.text") . 
					" LIKE " . $this->db->tidyInput("%$search1%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_note.text") . 
					" LIKE " . $this->db->tidyInput("%$search2%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_note.text") . 
					" LIKE " . $this->db->tidyInput("%$search3%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_quote_text.text") . 
					" LIKE " . $this->db->tidyInput("%$search1%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_quote_text.text") . 
					" LIKE " . $this->db->tidyInput("%$search2%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_quote_text.text") . 
					" LIKE " . $this->db->tidyInput("%$search3%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_quote_comment.comment") . 
					" LIKE " . $this->db->tidyInput("%$search1%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_quote_comment.comment") . 
					" LIKE " . $this->db->tidyInput("%$search2%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_quote_comment.comment") . 
					" LIKE " . $this->db->tidyInput("%$search3%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_paraphrase_text.text") . 
					" LIKE " . $this->db->tidyInput("%$search1%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_paraphrase_text.text") . 
					" LIKE " . $this->db->tidyInput("%$search2%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_paraphrase_text.text") . 
					" LIKE " . $this->db->tidyInput("%$search3%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_paraphrase_comment.comment") . 
					" LIKE " . $this->db->tidyInput("%$search1%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_paraphrase_comment.comment") . 
					" LIKE " . $this->db->tidyInput("%$search2%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_paraphrase_comment.comment") . 
					" LIKE " . $this->db->tidyInput("%$search3%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_musing_text.text") . 
					" LIKE " . $this->db->tidyInput("%$search1%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_musing_text.text") . 
					" LIKE " . $this->db->tidyInput("%$search2%") . 
				" OR " . 
					$this->db->formatField("WKX_resource_musing_text.text") . 
					" LIKE " . $this->db->tidyInput("%$search3%") . 
				")"
			);
// If we are browsing a user bibliography, we return only results this bibliography
		if($useBib = $this->session->getVar("mywikindx_bibliography_use"))
		{
			$recordset = $this->db->select(array('WKX_user_bibliography'), array('bibliography'), 
				" WHERE " . $this->db->formatfield('id') . "=" . $this->db->tidyInput($useBib));
			$dbBibs = $this->db->fetchOne($recordset);
			$bibsArray = explode(",", $dbBibs);
			$bibCondition = "(" . $this->db->formatfield('WKX_resource.id') . " = ";
			foreach($bibsArray as $id)
			{
				if($id == $resourceId)
					continue;
				$conditionArray[] = $this->db->tidyInput($id);
			}
			if(!isset($conditionArray))
				return $pString;
			$bibCondition .= implode(" OR " . $this->db->formatfield('WKX_resource.id') . " = ", 
				$conditionArray) . ")";
			$sql .= " AND " . $bibCondition;
			$title = unserialize($this->session->getVar('mywikindx_bibliographies'));
			$link = $this->messages->text("resources", "citedResources", " " . $title[1]);
			$recordset = $this->db->query($sql);
			while($line = $this->db->loopRecordSet($recordset))
				$bibCitedResources[] = $line['resourceId'];
			if(isset($bibCitedResources))
			{
//				$pString .= TABLE:: tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();
//				$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
//				$pString .= TABLE::trStart();
				$pString = MISC::span(MISC::a("link", $link, 
					"index.php?action=listCiteProcess"), "small") . MISC::br();
//				$pString .= TABLE::trEnd();
//				$pString .= TABLE::tableEnd();
				$this->session->setVar("list_citeIds", join(",", $bibCitedResources));
				return $pString;
			}
		}
// Results from the Master Bibliography
		$link = $this->messages->text("resources", "citedResources", " " . 
			$this->messages->text("user", "masterBib"));
		$masterSql = $sql . " AND (" . $this->db->formatField('WKX_resource.id') . " != " . 
			$this->db->tidyInput($resourceId) . ")";
		$recordset = $this->db->query($masterSql);
		while($line = $this->db->loopRecordSet($recordset))
			$masterCitedResources[] = $line['resourceId'];
		if(isset($masterCitedResources))
		{
//			$pString .= TABLE:: tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();
//			$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
//			$pString .= TABLE::trStart();
			$pString = MISC::span(MISC::a("link", $link, "index.php?action=listCiteProcess"), "small") . 
				MISC::br();
//			$pString .= TABLE::trEnd();
//			$pString .= TABLE::tableEnd();
			$this->session->setVar("list_citeIds", join(",", $masterCitedResources));
		}
		return $pString;
	}
/*
* parse [cite]...[/cite] and format citations
* @author Mark Grimshaw
* @version 1
* @param string input text
* @return string parsed text
*/
	function parseCitations($text, $output, $citeLink = TRUE, $rtfBibExport = FALSE, $suwpExport = FALSE)
	{
// If no citations, return doing nothing
		if(strpos(strtolower($text), "[cite]") === FALSE)
			return $text;
//		if(!$this->cite)
//		{
			include_once("core/styles/CITESTYLE.php");
			$this->cite = new CITESTYLE($this->db, $output, $rtfBibExport);
//		}
/*		else // re-initialise some settings
		{
			$this->cite->pageStart = $this->cite->pageEnd = 
			$this->cite->preText = $this->cite->postText = $this->cite->citeIds = array();
			$this->cite->citeformat->initialise();
		}
*/
		if($suwpExport) // Exporting from the SUWP
		{
			$this->cite->citeformat->suwpExport = TRUE;
// Can't have footnotes within footnotes so remove [cite]...[/cite] tags from footnote tags
			if($this->cite->citeformat->style['citationStyle'] && ($output == 'rtf'))
			{
//				$oldText = FALSE;
//				while($oldText != $text)
//				{
//					$oldText = $text;
					$text = preg_replace_callback("/(\[footnote])(.*)(\[\/footnote\])/Us", 
						array($this, 'footnoteCallback'), $text);
//				}
			}
			if($this->cite->citeformat->style['endnoteStyle'] == 1)
			{
				$this->cite->citeformat->citeOffsets = preg_split("/\[cite\]/Uis", $text, -1, 			
					PREG_SPLIT_OFFSET_CAPTURE);
				array_shift($this->cite->citeformat->citeOffsets);
				$this->cite->citeformat->footnoteOffsets = preg_split("/\[footnote\]/Uis", $text, -1, 			
					PREG_SPLIT_OFFSET_CAPTURE);
				array_shift($this->cite->citeformat->footnoteOffsets);
//				if(!empty($this->cite->citeformat->footnoteOffsets))
//					$this->cite->citeformat->footnoteOffsetIds = array();
			}
		}
		return $this->cite->start($text, $citeLink);
	}
// Callback for preg_replace_callback above
	function footnoteCallback($matches)
	{
		if(preg_match("/(.*)\[cite\].*\[\/cite\](.*)/Us", $matches[2], $null))
			return $matches[1] . preg_replace_callback("/\s*\[cite].*\[\/cite\](.*)/Us", 
					array($this, 'footnoteCiteCallback'), $matches[2]) . $matches[3];
		else
			return $matches[1] . $matches[2] . $matches[3];
	}
	function footnoteCiteCallback($matches)
	{
		return $matches[1];
	}
// write input to session
	function writeSession()
	{
// First, write all input with 'citeSearch_' prefix to session
		foreach($this->vars as $key => $value)
		{
			if(preg_match("/^citeSearch_/", $key))
			{
// Is this a multiple select box input?  If so, multiple choices are written to session as 
// comma-delimited string (no spaces).
// Don't write any FALSE or '0' values.
				if(is_array($value))
				{
					if(!$value[0] || ($value[0] == $this->messages->text("misc", "ignore")))
						unset($value[0]);
					if(empty($value))
					{
						$this->session->delVar($key);
						continue;
					}
					$value = implode(",", $value);
				}
				if(!trim($value))
					continue;
				$temp[$key] = trim($value);
			}
		}
// remove search_type, search_partial and search_word if not checked or empty
		if(isset($temp))
		{
			if(!array_key_exists('citeSearch_partial', $temp))
				$this->session->delVar('citeSearch_partial');
			if(!array_key_exists('citeSearch_word', $temp))
				$this->session->delVar('citeSearch_word');
			if(isset($temp))
				$this->session->writeArray($temp);
		}
	}
// validate user input - method, word and field are required.
// Must have at least one of creator, keyword, searchWord.
	function checkInput()
	{
		$this->writeSession();
		$validInput = FALSE;
		if(!array_key_exists("citeSearch_method", $this->vars))
			$this->session->setVar('citeSearch_method', "OR");
		if(!array_key_exists("citeSearch_creatorMethod", $this->vars))
			$this->session->setVar('citeSearch_creatorMethod', "OR");
		if(!array_key_exists("citeSearch_fieldMethod", $this->vars))
			$this->session->setVar('citeSearch_fieldMethod', "OR");
		if(!array_key_exists("citeSearch_keywordMethod", $this->vars))
			$this->session->setVar('citeSearch_keywordMethod', "OR");
		if(!array_key_exists("citeSearch_field", $this->vars))
			$this->session->setVar('citeSearch_field', "title");
		if(array_key_exists("citeSearch_word", $this->vars) && trim($this->vars["citeSearch_word"]))
			$validInput = TRUE;
		if(array_key_exists("citeSearch_creator", $this->vars) && 
			((sizeof($this->vars['citeSearch_creator']) > 1) || 
			$this->vars['citeSearch_creator'][0]))
			$validInput = TRUE;
		if(array_key_exists("citeSearch_keyword", $this->vars) && 
			((sizeof($this->vars['citeSearch_keyword']) > 1) || 
			$this->vars['citeSearch_keyword'][0]))
			$validInput = TRUE;
		if(!$validInput)
			$this->badInput($this->errors->text("inputError", "missing"));
		return $this->session->getArray("citeSearch");
	}
// Error handling for cite search popup
	function badInput($error)
	{
		$this->display($error);
	}
}
?>
